package cn.chencq.demo.consumer;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.demo.DemoHandler;
import cn.chencq.demo.ProcessMsgHelper;
import cn.chencq.demo.constant.MqConfig;
import cn.chencq.demo.constant.QueueName;
import cn.chencq.mq.ConsumerHandler;
import cn.chencq.mq.MQUtil;
import cn.chencq.mq.MQUtil.ExchangeType;

public class MqConsumer {

	private static final Logger LOGGER = LoggerFactory.getLogger(MqConsumer.class);

	private static final String EXCHANGE = MqConfig.getExchange();

	/**
	 * 启动线程，启动多个Work-Consumer耗费消息
	 */
	public static void startWorkConsumer() {
		try {

			// 集群名称
			String cluster = MqConfig.getClusterName();
			MQUtil.exchangeDeclare(cluster, EXCHANGE, ExchangeType.DIRECT);

			List<ProcessMsgHelper> helpers = new ArrayList<ProcessMsgHelper>();

			String work = "Ad-Info-Work";
			helpers = getMsgHelper(helpers, 
					cluster, 
					EXCHANGE, 
					QueueName.DEMO_INFO.getQueue(), 
					work, 
					MqConfig.getRoutingKey(), 
					new DemoHandler(work));

			// 开启多个线程
			for (ProcessMsgHelper helper : helpers) {
				new Thread(helper).start();
			}

			LOGGER.info("工作队列Work-Consumer启动完毕.");

		} catch (Exception e) {
			LOGGER.error("启动Work-Consumer异常", e);
			e.printStackTrace();
		}

	}

	/**
	 * 获取 MsgHelper
	 * 
	 * @param msgHelpers
	 * @param cluster
	 * @param exchange
	 * @param queue
	 * @param work
	 * @param routingKey
	 * @param handler
	 * @return
	 */
	private static List<ProcessMsgHelper> getMsgHelper(List<ProcessMsgHelper> msgHelpers,
			String cluster, String exchange, String queue, String work, String routingKey, ConsumerHandler handler) {

		try {
			// 队列声明
			MQUtil.queueDeclare(cluster, queue);
			// 队列绑定
			MQUtil.queueBind(cluster, queue, exchange, routingKey);

			msgHelpers.add(new ProcessMsgHelper(cluster, handler, work, queue));
		} catch (Exception e) {
			LOGGER.error("Get MsgHelper Exception", e);
		}

		return msgHelpers;
	}

}
